package org.mclll.xwangplugin.resourcePack.listener;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.th0rgal.oraxen.api.events.OraxenPackUploadedEvent;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.mclll.xwangplugin.MclllCustom;
import org.mclll.xwangplugin.log.GlobalLog;
import org.mclll.xwangplugin.log.LoggerFactory;
import org.mclll.xwangplugin.resourcePack.NetWork;
import org.mclll.xwangplugin.resourcePack.config.PackConfig;

/**
 * @author llB
 * @date 2024-06-21 08:30
 * @description todo
 */
public class PackListener implements Listener {

    private MclllCustom mclllCustom;
    private final Long EFFECTIVE_TIME = 50 * 60 * 1000L;
    private Long tokenLastFlashTime;
    private String token;

    public PackListener(MclllCustom mclllCustom) {
        this.mclllCustom = mclllCustom;
    }

//    @EventHandler
//    public void packListener(ItemsAdderPackCompressedEvent event) {
//        if (!PackConfig.getPlayerOnJoinSend()) {
//            return;
//        }
//        NetWork.upPack(mclllCustom.getDataFolder(), null);
//    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        if (!PackConfig.getPlayerOnJoinSend()) {
            return;
        }
        Bukkit.getScheduler().scheduleSyncDelayedTask(mclllCustom, () -> {
            NetWork.setPlayerPack(event.getPlayer());
        }, 20);
    }

    @EventHandler
    public void onOraxenUploaded(OraxenPackUploadedEvent event) {
        flashCdn(event.getUrl());
    }


    private void flashCdn(String url) {
        String param = "{\"auth\":{\"identity\":{\"methods\":[\"password\"],\"password\":{\"user\":{\"name\":\"hw59325149\",\"password\":\"wang1647021799\",\"domain\":{\"name\":\"hw59325149\"}}}},\"scope\":{\"domain\":{\"name\":\"hw59325149\"}}}}";
        if (tokenLastFlashTime == null || System.currentTimeMillis() - tokenLastFlashTime > EFFECTIVE_TIME) {
            HttpResponse execute = HttpRequest.post("https://iam.myhuaweicloud.com/v3/auth/tokens")
                    .body(param, "application/json")
                    .timeout(10 * 1000)
                    .execute();
            token = execute.header("X-Subject-Token");
            tokenLastFlashTime = System.currentTimeMillis();
        }


        String flashUrl = "{\"refresh_task\":{\"type\":\"file\",\"urls\":[\"%s\"]}}";
        HttpResponse response = HttpRequest.post("https://cdn.myhuaweicloud.com/v1.0/cdn/content/refresh-tasks")
                .header("X-Auth-Token", token)
                .body(String.format(flashUrl, url), "application/json")
                .timeout(10 * 1000)
                .execute();

        String taskId = JSON.parseObject(response.body()).getString("refresh_task");
        String checkUrl = "https://cdn.myhuaweicloud.com/v1.0/cdn/historytasks/%s/detail";
        Integer succeed, processing;
        do {
            HttpResponse statusRes = HttpRequest.get(String.format(checkUrl, taskId))
                    .header("X-Auth-Token", token)
                    .timeout(10 * 1000)
                    .execute();
            JSONObject resBody = JSON.parseObject(statusRes.body());
            succeed = resBody.getInteger("succeed");
            processing = resBody.getInteger("processing");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        } while (processing != 0);
        if (succeed == 1) {
            LoggerFactory.get(GlobalLog.class).info("url刷新成功");
        } else {
            LoggerFactory.get(GlobalLog.class).info("url刷新失败");
        }
    }
}
